<!-- 添加推广链接 -->
<!-- 添加推广链接 -->
<template>
  <div>
    <el-dialog v-model="dialogVisible" alignCenter width="1080px" title="回传模板" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
      <el-form ref="elFormRef" :validateOnRuleChange="false" :model="formData" scrollToError :rules="rules" style="width: 100%; min-height: 580px">
        <div v-auto-animate style="width: 100%">
          <el-form-item label="模板名称" labelWidth="13em" prop="iaaRuleName">
            <el-input v-model="formData.iaaRuleName" maxlength="20" placeholder="请输入回传模版名称"></el-input>
          </el-form-item>
          <el-form-item label="回传模式" labelWidth="13em" prop="timeScope">
            <box-from-border>
              <el-radio-group v-model="formData.iaaBackType" style="display: flex; align-items: flex-start; justify-content: flex-start">
                <el-radio label="关键行为模式" :value="1"></el-radio>
                <el-radio label="ROI变现模式" :value="2"></el-radio>
              </el-radio-group>
            </box-from-border>
          </el-form-item>
          <template v-if="formData.iaaBackType === 1">
            <el-form-item label="时间窗口" labelWidth="13em" prop="timeScope">
              <box-from-border>
                <el-radio-group v-model="formData.timeScope" style="display: flex; align-items: flex-start; justify-content: flex-start">
                  <el-radio label="24小时" :value="1"></el-radio>
                  <el-radio label="自然日" :value="2"></el-radio>
                  <el-radio label="自然日+3h" :value="3"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <el-form-item label="关键行为指标" labelWidth="13em" prop="behavioralType">
              <box-from-border>
                <el-checkbox-group v-model="formData.behavioralType" style="display: flex; align-items: flex-start; justify-content: flex-start">
                  <el-checkbox label="IPU" :value="1"></el-checkbox>
                  <el-checkbox label="ARPU" :value="2"></el-checkbox>
                  <el-checkbox label="平均eCPM" :value="3"></el-checkbox>
                  <el-checkbox label="最大eCPM" :value="4"></el-checkbox>
                </el-checkbox-group>
              </box-from-border>
            </el-form-item>
            <div v-if="formData.behavioralType.includes(1)" style="display: flex; width: 100%">
              <el-form-item label="IPU指标-最小值" labelWidth="13em" labelPosition="right" prop="ipuMinValue" style="flex: 1">
                <base-input-number
                  v-model="formData.ipuMinValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入IPU指标的最小值"
                ></base-input-number>
              </el-form-item>
              <el-form-item label="IPU指标-最大值" labelWidth="13em" labelPosition="right" prop="ipuMaxValue" style="flex: 1">
                <base-input-number
                  v-model="formData.ipuMaxValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入IPU指标的最大值"
                ></base-input-number>
              </el-form-item>
            </div>
            <div v-if="formData.behavioralType.includes(2)" style="display: flex; width: 100%">
              <el-form-item label="ARPU指标-最小值" labelWidth="13em" labelPosition="right" prop="arpuMinValue" style="flex: 1">
                <base-input-number
                  v-model="formData.arpuMinValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入ARPU指标的最小值"
                ></base-input-number>
              </el-form-item>
              <el-form-item label="ARPU指标-最大值" labelWidth="13em" labelPosition="right" prop="arpuMaxValue" style="flex: 1">
                <base-input-number
                  v-model="formData.arpuMaxValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入ARPU指标的最大值"
                ></base-input-number>
              </el-form-item>
            </div>
            <div v-if="formData.behavioralType.includes(3)" style="display: flex; width: 100%">
              <el-form-item label="平均eCPM指标-最小值" labelWidth="13em" labelPosition="right" prop="avgEcpmMinValue" style="flex: 1">
                <base-input-number
                  v-model="formData.avgEcpmMinValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入平均eCPM指标的最小值"
                ></base-input-number>
              </el-form-item>
              <el-form-item label="平均eCPM指标-最大值" labelWidth="13em" labelPosition="right" prop="avgEcpmMaxValue" style="flex: 1">
                <base-input-number
                  v-model="formData.avgEcpmMaxValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入平均eCPM指标的最大值"
                ></base-input-number>
              </el-form-item>
            </div>
            <div v-if="formData.behavioralType.includes(4)" style="display: flex; width: 100%">
              <el-form-item label="最大eCPM指标-最小值" labelWidth="13em" prop="maxEcpmMinValue" style="flex: 1">
                <base-input-number
                  v-model="formData.maxEcpmMinValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入最大eCPM指标的最小值"
                ></base-input-number>
              </el-form-item>
              <el-form-item label="最大eCPM指标-最大值" labelWidth="13em" labelPosition="right" prop="maxEcpmMaxValue" style="flex: 1">
                <base-input-number
                  v-model="formData.maxEcpmMaxValue"
                  verify="add_float"
                  :min="0"
                  :decimals="2"
                  placeholder="请输入最大eCPM指标的最大值"
                ></base-input-number>
              </el-form-item>
            </div>
            <el-form-item label="回传方式" labelWidth="13em" prop="backWay">
              <box-from-border>
                <el-radio-group v-model="formData.backWay" style="display: flex; align-items: flex-start; justify-content: flex-start">
                  <el-radio label="全部回传" :value="1"></el-radio>
                  <el-radio label="自定义" :value="2"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <div v-if="formData.backWay === 2" style="margin-left: 6em">
              <div style="display: flex; flex-direction: row; place-items: center center; justify-content: center; margin-bottom: 18px">
                <span style="margin-left: 6px">每</span>
                <el-form-item label="" labelWidth="8px" prop="backDenominatorNum" style="flex: 1; margin-bottom: 0">
                  <base-input-number
                    v-model="formData.backDenominatorNum"
                    verify="add_int_or_zero"
                    :min="0"
                    :decimals="0"
                    placeholder="请输入笔数"
                  ></base-input-number>
                </el-form-item>
                <span style="margin-left: 6px">笔订单,前</span>
                <el-form-item label="" labelWidth="8px" prop="backNumeratorNum" style="flex: 1; margin-bottom: 0">
                  <base-input-number
                    v-model="formData.backNumeratorNum"
                    verify="add_int_or_zero"
                    :min="0"
                    :decimals="0"
                    placeholder="请输入笔数"
                  ></base-input-number>
                </el-form-item>
                <span style="margin-left: 6px">笔回传,余下{{ formData.backDenominatorNum - formData.backNumeratorNum }}笔不回传</span>
              </div>
            </div>
          </template>
        </div>
      </el-form>
      <el-button type="success" style="width: 100%" :loading="loading" :disabled="loading" @click="submit">提交</el-button>
    </el-dialog>
    <page-select-template ref="pageSelectTemplateRef"></page-select-template>
  </div>
</template>

<script setup lang="ts">
  import { vAutoAnimate } from '@formkit/auto-animate/vue';
  import { type EditAiiBackTemplateRequest, type PdtIaaBackTemplateDTO, addIaaBackTemplateAxios, editIaaBackTemplateAxios } from '@/api/marketing-management';
  import PageSelectTemplate from '@/components/page/page-select-template/page-select-template.vue';
  import type { FormInstance, FormItemRule, FormRules } from 'element-plus';

  type $EditShowData = {
    /** 操作 */
    action: 'edit';
    row: PdtIaaBackTemplateDTO;
    /** 审核后的回调 */
    callBack?: () => void;
  };

  type $AddShowData = {
    /** 操作 */
    action: 'add';
    /** 审核后的回调 */
    callBack?: () => void;
  };
  type $ShowData = $AddShowData | $EditShowData;
  let callBack: $ShowData['callBack'] | undefined = undefined;

  const elFormRef: Ref<FormInstance | null> = ref(null);
  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });
  const dialogVisible = ref(false);
  const pageSelectTemplateRef: Ref<InstanceType<typeof PageSelectTemplate> | null> = ref(null);
  const loading = ref(false);
  const action = ref<'add' | 'edit'>('add');
  const productTemplateName = ref('');

  type FormData = Omit<EditAiiBackTemplateRequest, 'behavioralType' | 'iaaBackTemplateId'> & { behavioralType: number[]; iaaBackTemplateId?: number };

  const formData = ref<FormData>({
    iaaBackTemplateId: undefined,
    iaaRuleName: '',
    iaaBackType: 1,
    timeScope: 1,
    behavioralType: [1, 2, 3, 4],
    ipuMinValue: null,
    ipuMaxValue: null,
    arpuMinValue: null,
    arpuMaxValue: null,
    avgEcpmMinValue: null,
    avgEcpmMaxValue: null,
    maxEcpmMinValue: null,
    maxEcpmMaxValue: null,
    backWay: 1,
    backNumeratorNum: 1,
    backDenominatorNum: 1,
  });

  const rules = computed<FormRules>(() => {
    const _rules: FormRules = {
      iaaRuleName: [{ required: true, type: 'string', message: '请输入模版名称', trigger: ['blur', 'change'] }],
      timeScope: [
        { required: true, type: 'number', message: `请选择位置`, trigger: ['blur', 'change'] },
        { required: true, type: 'enum', enum: [1, 2, 3], message: `时间窗口不合法`, trigger: ['blur', 'change'] },
      ],
      behavioralType: [
        { required: true, type: 'array', message: `关键行为配置不合法`, trigger: ['blur', 'change'] },
        { min: 1, type: 'array', message: `最少选择一个关键行为指标`, trigger: ['blur', 'change'] },
      ],

      backNumeratorNum: [
        { required: true, type: 'number', message: `请输入笔数`, trigger: ['blur', 'change'] },
        { required: true, type: 'integer', min: 0, message: `笔数不合法`, trigger: ['blur', 'change'] },
      ],
      backDenominatorNum: [
        { required: true, type: 'number', message: `请输入笔数`, trigger: ['blur', 'change'] },
        { required: true, type: 'integer', min: 0, message: `笔数不合法`, trigger: ['blur', 'change'] },
      ],
      ipuMinValue: [{ type: 'number', min: 0, message: `IPU指标最小值不合法`, trigger: ['blur', 'change'] }],
      ipuMaxValue: [{ type: 'number', min: 0, message: `IPU指标最大值不合法`, trigger: ['blur', 'change'] }],
      arpuMinValue: [{ type: 'number', min: 0, message: `ARPU指标最小值不合法`, trigger: ['blur', 'change'] }],
      arpuMaxValue: [{ type: 'number', min: 0, message: `ARPU指标最大值不合法`, trigger: ['blur', 'change'] }],
      avgEcpmMinValue: [{ type: 'number', min: 0, message: `平均eCPM指标最小值不合法`, trigger: ['blur', 'change'] }],
      avgEcpmMaxValue: [{ type: 'number', min: 0, message: `平均eCPM指标最大值不合法`, trigger: ['blur', 'change'] }],
      maxEcpmMinValue: [{ type: 'number', min: 0, message: `最大eCPM指标最小值不合法`, trigger: ['blur', 'change'] }],
      maxEcpmMaxValue: [{ type: 'number', min: 0, message: `最大eCPM指标最大值不合法`, trigger: ['blur', 'change'] }],
    };

    if (formData.value.behavioralType.includes(1)) {
      (_rules.ipuMinValue as FormItemRule[]).push({
        required: true,
        type: 'number',
        message: `请输入最小值`,
        trigger: ['blur', 'change'],
      });
    }

    if (formData.value.behavioralType.includes(2)) {
      (_rules.arpuMinValue as FormItemRule[]).push({
        required: true,
        type: 'number',
        message: `请输入最小值`,
        trigger: ['blur', 'change'],
      });
    }
    if (formData.value.behavioralType.includes(3)) {
      (_rules.avgEcpmMinValue as FormItemRule[]).push({
        required: true,
        type: 'number',
        message: `请输入最小值`,
        trigger: ['blur', 'change'],
      });
    }
    if (formData.value.behavioralType.includes(4)) {
      (_rules.maxEcpmMinValue as FormItemRule[]).push({
        required: true,
        type: 'number',
        message: `请输入最小值`,
        trigger: ['blur', 'change'],
      });
    }
    if (typeof formData.value.ipuMinValue === 'number' && typeof formData.value.ipuMaxValue === 'number') {
      (_rules.ipuMinValue as FormItemRule[]).push({
        type: 'number',
        min: 0,
        max: formData.value.ipuMaxValue,
        message: `最小值不能大于最大值`,
        trigger: ['blur', 'change'],
      });
      _rules.ipuMaxValue = [{ type: 'number', min: formData.value.ipuMinValue, message: `最大值不能小于最小值`, trigger: ['blur', 'change'] }];
    }
    if (typeof formData.value.arpuMinValue === 'number' && typeof formData.value.arpuMaxValue === 'number') {
      (_rules.arpuMinValue as FormItemRule[]).push({
        type: 'number',
        min: 0,
        max: formData.value.arpuMaxValue,
        message: `最小值不能大于最大值`,
        trigger: ['blur', 'change'],
      });
      _rules.arpuMaxValue = [{ type: 'number', min: formData.value.arpuMinValue, message: `最大值不能小于最小值`, trigger: ['blur', 'change'] }];
    }
    if (typeof formData.value.avgEcpmMinValue === 'number' && typeof formData.value.avgEcpmMaxValue === 'number') {
      (_rules.avgEcpmMinValue as FormItemRule[]).push({
        type: 'number',
        min: 0,
        max: formData.value.avgEcpmMaxValue,
        message: `最小值不能大于最大值`,
        trigger: ['blur', 'change'],
      });
      _rules.avgEcpmMaxValue = [{ type: 'number', min: formData.value.avgEcpmMinValue, message: `最大值不能小于最小值`, trigger: ['blur', 'change'] }];
    }
    if (typeof formData.value.maxEcpmMinValue === 'number' && typeof formData.value.maxEcpmMaxValue === 'number') {
      (_rules.maxEcpmMinValue as FormItemRule[]).push({
        type: 'number',
        min: 0,
        max: formData.value.maxEcpmMaxValue,
        message: `最小值不能大于最大值`,
        trigger: ['blur', 'change'],
      });
      _rules.maxEcpmMaxValue = [{ type: 'number', min: formData.value.maxEcpmMinValue, message: `最大值不能小于最小值`, trigger: ['blur', 'change'] }];
    }

    if (typeof formData.value.backNumeratorNum === 'number' && typeof formData.value.backDenominatorNum === 'number') {
      (_rules.backNumeratorNum as FormItemRule[]).push({
        type: 'number',
        min: 0,
        max: formData.value.backDenominatorNum,
        message: `总笔数不能小于前几笔`,
        trigger: ['blur', 'change'],
      });
      (_rules.backDenominatorNum as FormItemRule[]).push({
        type: 'integer',
        min: formData.value.backNumeratorNum,
        message: `前几笔不能大于总笔数`,
        trigger: ['blur', 'change'],
      });
    }
    return _rules;
  });

  /**
   * 提交
   */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      try {
        loading.value = true;
        const data: Record<keyof FormData, any> = JSON.parse(JSON.stringify(formData.value));
        data.behavioralType = data.behavioralType.toString();
        if (action.value === 'edit') {
          await editIaaBackTemplateAxios(data);
        } else {
          data.iaaBackTemplateId = undefined;
          await addIaaBackTemplateAxios(data);
        }
        loading.value = false;
        typeof callBack === 'function' && callBack();
        hide();
      } catch (error) {
        loading.value = false;
        ElToast.error(error.msg || '提交失败，-BD001');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  /**
   * 显示
   */
  function show(data: $ShowData) {
    dialogVisible.value = true;
    callBack = data.callBack;
    pageLoad.loadState = false;
    action.value = data.action;
    if (data.action === 'edit') {
      const behavioralType = data.row.behavioralType ?? '1,2,3,4';
      const behavioralTypeArr: number[] = [];
      behavioralType.split(',').forEach((item) => {
        const num = parseInt(item);
        !isNaN(num) && behavioralTypeArr.push(num);
      });
      formData.value = {
        iaaBackTemplateId: data.row.iaaBackTemplateId ?? undefined,
        iaaRuleName: data.row.iaaRuleName ?? '',
        iaaBackType: data.row.iaaBackType ?? 1,
        timeScope: data.row.timeScope ?? 1,
        behavioralType: behavioralTypeArr,
        ipuMinValue: data.row.ipuMinValue ?? null,
        ipuMaxValue: data.row.ipuMaxValue ?? null,
        arpuMinValue: data.row.arpuMinValue ?? null,
        arpuMaxValue: data.row.arpuMaxValue ?? null,
        avgEcpmMinValue: data.row.avgEcpmMinValue ?? null,
        avgEcpmMaxValue: data.row.avgEcpmMaxValue ?? null,
        maxEcpmMinValue: data.row.maxEcpmMinValue ?? null,
        maxEcpmMaxValue: data.row.maxEcpmMaxValue ?? null,
        backWay: data.row.backWay ?? 1,
        backNumeratorNum: data.row.backNumeratorNum ?? 1,
        backDenominatorNum: data.row.backDenominatorNum ?? 1,
      };
    } else {
      productTemplateName.value = '';
      formData.value = {
        iaaRuleName: '',
        iaaBackType: 1,
        timeScope: 1,
        behavioralType: [1, 2, 3, 4],
        ipuMinValue: null,
        ipuMaxValue: null,
        arpuMinValue: null,
        arpuMaxValue: null,
        avgEcpmMinValue: null,
        avgEcpmMaxValue: null,
        maxEcpmMinValue: null,
        maxEcpmMaxValue: null,
        backWay: 1,
        backNumeratorNum: 1,
        backDenominatorNum: 1,
      };
    }
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  defineExpose({ show, hide });
</script>

<style scoped lang="scss">
  .content-vessel {
    display: grid;
    grid-template-columns: repeat(auto-fill, 259px);
    gap: 15px;
    place-content: center;
    width: 100%;
    padding-bottom: 15px;

    .content-box {
      overflow: hidden;
      cursor: pointer;
      background: $c-bg-block;
      border-radius: 10px;
      box-shadow: var(--my-box-shadow-fill);

      .title-box {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-around;
        width: 100%;
        padding: 10px 0;
      }
    }
  }
</style>
